//
// Created by v on 2019/10/23 下午4:24.
// Copyright (c) 2019 jmdvirus All rights reserved.
//
//     ******          *             *--*
//       ||            *             |
//       ||  *--*--*---*  * *-********--*
//    * //   *  *  *   *\ / ||  |  |    |
//     **    *  *  *---* *  *   *--* *--*
//

#include "CMTaskRunner.h"
#include "pthread.h"
#include <unistd.h>

CMTaskRunner::CMTaskRunner() { m_exit = false; }

CMTaskRunner::~CMTaskRunner() {}

void CMTaskRunner::registerTask(CMTaskRunnerInterface *task)
{
    m_lock.lock(__func__, __LINE__);
    m_tmpTasks.push_back(task);
    m_lock.unlock();
}

void *thread_run(void *args)
{
    CMTaskRunner *taskRunner = (CMTaskRunner *)args;
    while (!taskRunner->m_exit)
    {
        if (!taskRunner->m_tmpTasks.empty())
        {
            taskRunner->m_lock.lock(__func__, __LINE__);
            std::vector<CMTaskRunnerInterface *>::iterator iter =
                taskRunner->m_tmpTasks.begin();
            for (; iter != taskRunner->m_tmpTasks.end(); iter++)
            {
                taskRunner->m_tasks.push_back(*iter);
            }
            taskRunner->m_tmpTasks.clear();
            taskRunner->m_lock.unlock();
        }
        if (taskRunner->m_tasks.empty())
        {
            usleep(500000);
            continue;
        }

        std::vector<CMTaskRunnerInterface *>::iterator iter =
            taskRunner->m_tasks.begin();
        for (; iter != taskRunner->m_tasks.end(); iter++)
        {
            CMTaskRunnerInterface *r = *iter;
            r->run();
        }
        usleep(40000);
    }
    return NULL;
}

int CMTaskRunner::createTaskRunner()
{
    // create thread to run task

    pthread_t pid;
    int       ret = pthread_create(&pid, NULL, thread_run, this);
    if (ret < 0)
    {
        return -1;
    }
    return 0;
}